package mq

import (
	"fmt"
	"github.com/micro/go-micro/v2/util/log"
	"github.com/streadway/amqp"
	"gomicrodemo/common"
)

var (
	mqEntry *common.Consumer
	msgs    <-chan amqp.Delivery
	err     error
)

func InitSubcribe() () {
	//获取消费者，调用common的NewAmqoChannel
	mqEntry = common.NewAmqpChannel()

	//声明一个队列用来保存消息并传给消费者
	queue, err := mqEntry.Channel.QueueDeclare( //绑定队列
		common.BindingQueue1,
		true,
		false,
		false,
		false,
		nil,
	)
	if err != nil {
		log.Errorf("QueueDeclare fail msg:%v", err)
	}

	//声明一个交换机用于 ↑ 队列
	if err = mqEntry.Channel.QueueBind(
		queue.Name,
		common.Topic1,
		common.Exchange,
		false,
		nil,
	); err != nil {
		log.Errorf("QueueBind fail msg:%v", err)
	}

	if msgs, err = mqEntry.Channel.Consume(
		common.BindingQueue1,
		mqEntry.Tag,
		false,
		false,
		false,
		false,
		nil,
	); err != nil {
		log.Errorf("channel consume fail msg:%v", err)
	}

	msgsMap := common.Handle(msgs, mqEntry.Done)
	for _, v := range msgsMap {
		fmt.Printf("监听到%v消息", common.BindingQueue1)
		fmt.Println(v)
	}

}
